package test;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import tools.Config;

/**
 * Servlet implementation class ReadDB
 */
public class ReadDB extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ReadDB(){}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		process(request, response);}
	
	protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		
		
		DataSource ds;
		Connection con = null;
		
		try{
			Context ctx = new InitialContext();
			ds = (DataSource) ctx.lookup(Config.ctxLookup);
			con = ds.getConnection();
			Statement stmt = con.createStatement();
		
		
			ResultSet rs = stmt.executeQuery("SELECT * FROM Location");
			out.println("<h3>Location</h3>");out.println("<h3>Location</h3>");
			while (rs.next()){
				out.println("Id : "+rs.getInt("id")+
							" x : "+rs.getDouble("x")+
							" y : "+rs.getDouble("y")+
							"map id : "+rs.getInt("map_id")+
							"<br>");
			}
			
			rs = stmt.executeQuery("SELECT * FROM Rssi");
			out.println("<h3>Rssi</h3>");
			while (rs.next()){
				out.println("Loc id : "+rs.getInt("id_loc")+
							" AP id : "+rs.getDouble("id_ap")+
							" Val : "+rs.getDouble("avg_val")+
							"<br>");
			}
		}catch (Exception e){//Catch exception if any
			System.err.println("Error: " + e.getMessage());
		}
	}

}
